package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户端
 * @author Xiao
 * @date 2021/9/29
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    //注入RedisTemplate对象
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信验证码
     * @param request
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsgApi(HttpServletRequest request, @RequestBody User user) {
        String phone = user.getPhone();
        //将生成的验证码存入session中并发送
        /*String codeInSession = userService.sendMsgApi(phone);
        request.getSession().setAttribute(phone, codeInSession);
        log.info("phone:{}, codeInSession:{}", phone, codeInSession);*/
        //将生成的验证码存入redis中并发送
        String codeInRedis = userService.sendMsgApi(phone);
        redisTemplate.opsForValue().set(phone, codeInRedis, 5L, TimeUnit.MINUTES);
        log.info("phone:{}, codeInRedis:{}", phone, codeInRedis);
        return R.success("验证码已发送！");
    }

    /**
     * 登陆
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<User> loginApi(HttpServletRequest request, @RequestBody Map map) {
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        log.info("phone:{}, code:{}", phone, code);
        //从session中获取验证码
        /*String codeInSession = (String) request.getSession().getAttribute(phone);
        User user = userService.loginApi(phone, code, codeInSession);*/
        //从redis中获取验证码
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone);
        User user = userService.loginApi(phone, code, codeInRedis);
        if (user != null) {
            request.getSession().setAttribute("loginUserId", user.getId());
            //如果登录成功则删除缓存在redis中的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登陆失败，验证码错误！");
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginoutApi(HttpServletRequest request) {
        log.info("退出登录！");
        //从session中删除用户信息
        request.getSession().removeAttribute("loginUser");
        //request.getSession().invalidate();
        return R.success("您已退出登录！");
    }

    /**
     * 获取当前登陆的用户信息
     * @return
     */
    @GetMapping("/userMsg")
    public R<User> getUserMsgApi() {
        User user = userService.getUserMsgApi();
        return R.success(user);
    }
}
